class MoistureTrend {
    constructor() {
        this.trendChart = null;
        this.currentTimeRange = '24h';
        
        // 等待 DOM 加载完成后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initialize());
        } else {
            this.initialize();
        }
    }

    initialize() {
        this.initializeChart();
        this.initializeEventListeners();
        this.updateData();
    }

    initializeChart() {
        const ctx = document.getElementById('moistureTrendChart');
        if (ctx) {
            this.trendChart = new Chart(ctx.getContext('2d'), {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: '土壤墒情 (%)',
                        data: [],
                        borderColor: 'rgba(24, 144, 255, 1)',
                        backgroundColor: 'rgba(24, 144, 255, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100
                        }
                    },
                    plugins: {
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    }
                }
            });
        }
    }

    initializeEventListeners() {
        // 时间范围按钮点击事件
        document.querySelectorAll('.time-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                document.querySelectorAll('.time-btn').forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                
                const range = btn.dataset.range;
                if (range === 'custom') {
                    document.querySelector('.custom-date-range').style.display = 'flex';
                } else {
                    document.querySelector('.custom-date-range').style.display = 'none';
                    this.currentTimeRange = range;
                    this.updateData();
                }
            });
        });

        // 自定义日期范围应用按钮
        document.querySelector('.apply-btn').addEventListener('click', () => {
            const startDate = document.getElementById('start-date').value;
            const endDate = document.getElementById('end-date').value;
            if (startDate && endDate) {
                this.updateData(startDate, endDate);
            }
        });

        // 区域选择事件
        document.getElementById('area-trend-selector').addEventListener('change', (e) => {
            this.updateData();
        });

        // 异常类型筛选事件
        document.getElementById('anomaly-type-filter').addEventListener('change', (e) => {
            this.updateAnomalyRecords();
        });
    }

    generateTimeLabels(range) {
        const labels = [];
        const now = new Date();
        let interval;
        let count;

        switch (range) {
            case '24h':
                interval = 3600000; // 1小时
                count = 24;
                break;
            case '7d':
                interval = 86400000; // 1天
                count = 7;
                break;
            case '30d':
                interval = 86400000; // 1天
                count = 30;
                break;
            default:
                interval = 3600000;
                count = 24;
        }

        for (let i = count - 1; i >= 0; i--) {
            const time = new Date(now - i * interval);
            labels.push(this.formatTime(time, range));
        }

        return labels;
    }

    formatTime(date, range) {
        if (range === '24h') {
            return `${date.getHours()}:00`;
        } else {
            return `${date.getMonth() + 1}/${date.getDate()}`;
        }
    }

    generateMockData(count) {
        return Array.from({length: count}, () => 20 + Math.random() * 30);
    }

    updateData(startDate, endDate) {
        const areaId = document.getElementById('area-trend-selector').value;
        let labels, data;

        if (startDate && endDate) {
            // 处理自定义日期范围的数据
            const start = new Date(startDate);
            const end = new Date(endDate);
            const days = Math.ceil((end - start) / (1000 * 60 * 60 * 24));
            labels = Array.from({length: days}, (_, i) => {
                const date = new Date(start);
                date.setDate(date.getDate() + i);
                return `${date.getMonth() + 1}/${date.getDate()}`;
            });
            data = this.generateMockData(days);
        } else {
            // 处理预设时间范围的数据
            const count = this.currentTimeRange === '24h' ? 24 : 
                         this.currentTimeRange === '7d' ? 7 : 30;
            labels = this.generateTimeLabels(this.currentTimeRange);
            data = this.generateMockData(count);
        }

        // 更新趋势图
        this.updateTrendChart(labels, data);
        // 更新统计数据
        this.updateStats(data);
        // 更新异常记录
        this.updateAnomalyRecords();
    }

    updateTrendChart(labels, data) {
        this.trendChart.data.labels = labels;
        this.trendChart.data.datasets[0].data = data;
        this.trendChart.update();
    }

    updateStats(data) {
        const avg = data.reduce((a, b) => a + b, 0) / data.length;
        const max = Math.max(...data);
        const min = Math.min(...data);

        document.getElementById('trend-avg-moisture').textContent = avg.toFixed(1);
        document.getElementById('trend-max-moisture').textContent = max.toFixed(1);
        document.getElementById('trend-min-moisture').textContent = min.toFixed(1);

        // 更新最大最小值时间
        const maxIndex = data.indexOf(max);
        const minIndex = data.indexOf(min);
        document.getElementById('max-moisture-time').textContent = 
            this.trendChart.data.labels[maxIndex];
        document.getElementById('min-moisture-time').textContent = 
            this.trendChart.data.labels[minIndex];
    }

    updateAnomalyRecords() {
        const anomalyType = document.getElementById('anomaly-type-filter').value;
        const mockAnomalies = this.generateMockAnomalies(anomalyType);
        
        const tbody = document.getElementById('anomaly-records');
        tbody.innerHTML = mockAnomalies.map(record => `
            <tr>
                <td>${record.time}</td>
                <td>${record.area}</td>
                <td>${record.point}</td>
                <td>
                    <span class="status-tag ${record.type === '墒情偏高' ? 'warning' : 'danger'}">
                        ${record.type}
                    </span>
                </td>
                <td>${record.value}%</td>
                <td>${record.duration}</td>
            </tr>
        `).join('');
    }

    generateMockAnomalies(type) {
        const anomalies = [];
        const types = type === 'all' ? ['墒情偏高', '墒情偏低'] :
                     type === 'high' ? ['墒情偏高'] : ['墒情偏低'];

        for (let i = 0; i < 5; i++) {
            const anomaly = {
                time: new Date(Date.now() - Math.random() * 86400000 * 7).toLocaleString(),
                area: `区域${Math.ceil(Math.random() * 5)}`,
                point: `监测点${Math.ceil(Math.random() * 12)}`,
                type: types[Math.floor(Math.random() * types.length)],
                value: type === 'high' ? (40 + Math.random() * 20).toFixed(1) :
                       type === 'low' ? (10 + Math.random() * 10).toFixed(1) :
                       (Math.random() > 0.5 ? (40 + Math.random() * 20) : (10 + Math.random() * 10)).toFixed(1),
                duration: `${Math.ceil(Math.random() * 120)}分钟`
            };
            anomalies.push(anomaly);
        }

        return anomalies;
    }
}

// 创建全局实例
window.moistureTrend = new MoistureTrend(); 